<template>
    <div class="ml10 avatar">
        <!-- <form action=""></form> -->
        <input type="file" ref="file" class="file"  @change="uploadFile"  >
        <el-tooltip
            effect="dark"
            content="切换头像"
            placement="bottom-end"
            v-if="userInfo"
        >
            <el-avatar v-if="userInfo.avatar" :size="35" :src="userInfo.avatar.replace(/public/,baseURL)" @click="todoUpdate" />
            <el-avatar v-else :size="35" :src="circleUrl" @click="todoUpdate" />
        </el-tooltip>
    </div>
</template>


<script setup>
import { computed, ref } from "vue";
import {Http} from '@/api'
import {baseURL} from "@/api/request"
import{useStore} from "vuex"

const store = useStore()
const circleUrl = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png');
const file=ref()
const userInfo= computed(()=>store.state.userInfo)  // proxy 代理数据 
const todoUpdate=()=>{
 file.value.click()
}

// 上传文件
const uploadFile= async()=>{ 

    const fileData = file.value.files[0]
    console.log(fileData);
    const data=new FormData() //生成js表单数据
    
    data.append('file',fileData)  //需要上传的文件
    let res = await Http.uploadfiles(data)
    if(res.code==200){
        // 修改后端数据库
        let data = await Http.changeuserinfo({
                              
            avatar:res.path
        })

        // 前端修改
        // userInfo.avatar = res.path
        store.commit("getuserinfo",{...store.state.userInfo,avatar:res.path})
    }
}








</script>


<style lang="scss" scoped>
.avatar{
    cursor: pointer;
    .file{
        display: none;
    }
}
</style>